package com.tdkj.service.shop.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanGoodFavoriteDao;
import com.tdkj.model.shop.BeanGood;
import com.tdkj.model.shop.BeanGoodFavorite;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.shop.IBeanGoodFavoriteService;


@Component
public class BeanGoodFavoriteServiceImpl extends BaseService implements
		IBeanGoodFavoriteService {

	private  IBeanGoodFavoriteDao beanFavoriteDao;
    
	@Resource
	public void setBeanFavoriteDao(IBeanGoodFavoriteDao beanFavoriteDao) {
		this.beanFavoriteDao = beanFavoriteDao;
	}

	public IBeanGoodFavoriteDao getBeanFavoriteDao() {
		return beanFavoriteDao;
	}

	@Override
	public List<BeanGoodFavorite> getBeanGoodFavorites(Long userId) {
		BeanUser user = beanFavoriteDao.findById(userId, BeanUser.class);
		List<BeanGoodFavorite> beans = beanFavoriteDao.findByProperty("user", user, BeanGoodFavorite.class);
		return beans;
	}

	@Override
	public BeanGoodFavorite add(Long userId, Long goodId) throws ServiceException {
		
		String hql = " from " + BeanGoodFavorite.class.getName() + " as bean where bean.good.id='"+goodId+"' and bean.user.id='"+userId+"'";
		Query query = this.getBaseDao().getSession().createQuery(hql);
		if(query.list().size() > 0){
			throw new ServiceException("已收藏");
		}
		
		BeanUser user = beanFavoriteDao.findById(userId, BeanUser.class);
		BeanGood good = beanFavoriteDao.findById(goodId, BeanGood.class);
		
		BeanGoodFavorite bean = new BeanGoodFavorite();
		bean.setUser(user);
		bean.setGood(good);
		
		beanFavoriteDao.save(bean);
		return bean;
	}

	@Override
	public void remove(Long id) {
		BeanGoodFavorite bean = beanFavoriteDao.findById(id, BeanGoodFavorite.class);
		beanFavoriteDao.delete(bean);
	}
	
}
